package geektime.spring.cn.bothdatasource.bothdatasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
@Slf4j
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
		DataSourceTransactionManagerAutoConfiguration.class,
		JdbcTemplateAutoConfiguration.class})
public class BothdatasourceApplication {
	/**
	 *  入口
	 * @param args
	 */
	public static void main(String[] args) {
		SpringApplication.run(BothdatasourceApplication.class, args);
	}

	/**
	 * 读取数据源的配置属性
	 * @return
	 */
	@Bean
	@ConfigurationProperties("foo.datasource")
	public DataSourceProperties fooDataSourceProperties(){
		return  new DataSourceProperties();
	}

	/**
	 * 返回fooDataSource
	 * @return
	 */
	@Bean
	public DataSource fooDataSource(){
		DataSourceProperties dataSourceProperties = fooDataSourceProperties();
		log.info("foo  dataSourceProperties:" + dataSourceProperties.getUrl());
		return  dataSourceProperties.initializeDataSourceBuilder().build();
	}

	/**
	 * 返回事务
	 * @param fooDataSource
	 * @return
	 */
	@Bean
	@Resource
	public PlatformTransactionManager fooTxmanager(DataSource fooDataSource){
			return  new DataSourceTransactionManager(fooDataSource);
	}


	@Bean
	@ConfigurationProperties("bar.datasource")
	public DataSourceProperties barDataSourcePropeties(){
		return  new DataSourceProperties();
	}

	@Bean
	public DataSource barDataSource(){
		DataSourceProperties dataSourceProperties =  barDataSourcePropeties();
		log.info("bar dataSourcePropeties:" + dataSourceProperties.getUrl());
		return dataSourceProperties.initializeDataSourceBuilder().build();
	}

	@Bean
	@Resource
	public PlatformTransactionManager barTxManager(DataSource barDataSource){
		return  new DataSourceTransactionManager(barDataSource);
	}

}
